<template>
    <tm-app class="app">
        <view
            style="position: fixed; top: 0; width: 750rpx; background: #fff"
            :style="{ height: systemInfo.statusBarHeight + 'px' }"
        ></view>
        <view
            class="header"
            :style="{ top: systemInfo.statusBarHeight + 'px' }"
        >
            <image
                src="/static/firends/right.png"
                class="right"
                @tap="goBack"
            ></image>
            <text class="firend">申请加入群</text>
            <view></view>
        </view>

        <view
            class="content"
            :style="{ top: `calc(100rpx + ${systemInfo.statusBarHeight}px)` }"
        >
            <view class="box">
                <view class="title">发送加入群申请</view>
                <uni-easyinput
                    style="margin-top: 20rpx"
                    :inputBorder="false"
                    type="textarea"
                    maxlength="100"
                    trim
                    :autoHeight="true"
                    placeholderStyle="color:#ccc;font-size:30rpx;"
                    v-model="wording"
                    placeholder="附言（最多100个字）"
                ></uni-easyinput>
                <!-- <view class="amount d-flex a-center" v-if="!VER.ver">
                    <text>入群费用:</text>
                    <text
                        v-if="groupDetail.payAmount"
                        style="margin-lefg: 10rpx"
                        ><text style="font-size: 12px">¥</text
                        >{{ toYuan(groupDetail.payAmount) }}</text
                    >
                    <text v-else style="margin-lefg: 10rpx">免费</text>
                </view> -->

                <!-- <view
                    class="warn d-flex a-center"
                    v-if="!VER.ver && groupDetail.payAmount"
                >
                    <image class="icon_warn" src="/static/warn.png" />
                    <text>加入群后，48小时内退群可无条件全额退</text>
                </view> -->

                <!-- <tm-button v-if="inGroup&&!isVisitor" class="btn_main" :width="690" :shadow="0" :linear-color="['#64F1C5','#29DBA3']" linear="left" :fontSize="32" fontColor="#ffffff" :loading="addLoading" @tap="joinGroup" label="进入群"></tm-button>
                 <tm-button v-else class="btn_main" :width="690" :shadow="0" :linear-color="['#64F1C5','#29DBA3']" linear="left" :fontSize="32" fontColor="#ffffff" :loading="addLoading" @tap="joinGroup" :label="btnText"></tm-button> -->
            </view>
        </view>

        <view class="btn_bottom_box">
            <view
                v-if="inGroup && !isVisitor"
                class="btn_main_r"
                @tap="joinGroup"
            >
                <text class="text">进入群</text>
            </view>
            <view v-else class="btn_main_r" @tap="joinGroup">
                <text class="text">{{ btnText }}</text>
            </view>
            <view class="bottom_seat"></view>
        </view>

        <uni-popup
            v-if="!VER.ver"
            style="z-index: 200"
            ref="popup"
            :safe-area="false"
            :mask-click="true"
            @maskClick="maskClick"
        >
            <view class="bottom-popup">
                <view class="popup-title psr d-flex a-center j-center">
                    <view class="title-text">选择支付方式</view>
                    <image
                        @tap="close"
                        class="title-icon psa h-center"
                        src="/static/image/close.png"
                    ></image>
                </view>
                <template v-for="item in systemConfig.payType">
                    <view class="popup-row" @tap="selectPay(item)">
                        <view
                            class="row-content d-flex a-center"
                            :class="{
                                selected:
                                    selectedPayType.slimKey === item.slimKey,
                            }"
                        >
                            <image
                                v-if="selectedPayType.slimKey === item.slimKey"
                                class="selected-icon"
                                src="/static/image/payment-selected.png"
                            ></image>
                            <image
                                v-if="item.slimKey == 1"
                                class="content-img"
                                src="/static/image/WeChat.png"
                            ></image>
                            <image
                                v-if="item.slimKey == 2"
                                class="content-img"
                                src="/static/image/Alipay.png"
                            ></image>
                            <view class="content-type">
                                <view class="type-name d-flex a-center">
                                    <view class="name-text">{{
                                        item.slimValue
                                    }}</view>
                                </view>
                            </view>
                        </view>
                    </view>
                </template>
                <view class="popup-button">
                    <view class="btn_main_r" style="margin:0 auto;"  @tap="checkAndPayAmount">
                        <text class="text">
                            支付 ¥{{ toYuan(groupDetail.payAmount) }}
                        </text>
                    </view>
                    <view class="heightBox"></view>
				</view>
            </view>
        </uni-popup>
    </tm-app>

    <web-view
        :style="{ width: `1rpx`, height: `1rpx` }"
        :webview-styles="webviewStyles"
        src="/hybrid/html/ali.html"
    ></web-view>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import {
    onShow,
    onLoad,
    onUnload,
} from "@dcloudio/uni-app";
import { systemInfo as systemInfoStore } from "@/store/systemInfo";
import {
    getCircleDetail,
    vistorJoin,
    vistorToMember,
    isInGroupBlacklist,
    vistorQuit
} from "@/api/api";
import { userData as userDataStore } from "@/store/userData";
import { showLoading, closeLoading, wait, closeWebview } from "@/utils/utils";
import { pay as h5pay } from "@/hooks/h5pay";
import { pay } from "@/hooks/pay";
import { systemConfig as systemConfigStore } from "@/store/systemConfig";
import {
    handleJoinGroup,
    isGroupJoined,
    getGroupProfile,
    handleJumpToChat,
} from "@/hooks/imHooks";
import { centToYuan } from "@/utils/format";
import { imStore } from "@/store/imStore";
import { ver } from "@/store/ver";
const VER = ver();
const userData: any = userDataStore();
const systemInfo: any = systemInfoStore();
const systemConfig: any = systemConfigStore();
const groupId = ref("");

const wording = ref("");
const joinGroupLoading = ref(false);

const btnText = ref("");

const popup = ref();
const isVisitor = ref(false);
const inGroup = ref(false);


const webviewStyles = ref({
    width: "1",
    height: "1",
});

const toYuan = (num: number) => {
    return Number(centToYuan(num));
};

const open = () => {
    // var EnvUtils = plus.android.importClass("com.alipay.sdk.app.EnvUtils");
    // EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
    popup.value.open("bottom");
    //fix.value = true;
};

const close = () => {
    popup.value.close();
    joinGroupLoading.value = false;

    //fix.value = false;
};
const maskClick = () => {
    joinGroupLoading.value = false;
    //fix.value = false;
};

const handleisGroupJoined = async () => {
    if (!uni.$chat_isSDKReady) {
        setTimeout(() => {
            handleisGroupJoined();
        }, 20);
        return;
    }
    inGroup.value = await isGroupJoined(userData.id, groupId.value) as boolean;
};

const IsInGroupBlacklist = async () => {
    const params = {
        userId: userData.id,
        groupId: groupId.value,
    };
    const res:any = await isInGroupBlacklist(params);

    const { flag, data } = res;
    if (flag !== 1) {
        return false;
    }
    return data.data;
};

const joinGroup = async () => {

    if(groupDetail.value.joinOption===uni.$TIM.TYPES.JOIN_OPTIONS_DISABLE_APPLY){
        uni.showToast({
            icon: "none",
            title: "该群禁止任何人加入",
            duration: 3000,
        });
        return;
    }

    if (joinGroupLoading.value) {
        return;
    }

    if (!groupDetail.value.payAmount) {
        showLoading();
    }

    joinGroupLoading.value = true;

    const inGroupBlackList = await IsInGroupBlacklist();
    if (inGroupBlackList) {
        closeLoading();
        joinGroupLoading.value = false;
        uni.showToast({
            icon: "none",
            title: "你已被群主拉入黑名单",
            duration: 1500,
        });
        return;
    }

    const isJoined: boolean = await isGroupJoined(
        userData.id,
        groupId.value
    ).catch(() => {
        closeLoading();
    }) as boolean;

    if (isJoined && !isVisitor.value) {
        closeLoading();
        uni.showToast({
            icon: "none",
            title: "您已经在这个群~",
            duration: 1500,
        });
        uni.$emit("groupJoined");
        joinGroupLoading.value = false;
        goChat(false);
        return;
    }

    let msg = `你好，我是${userData.nickName}`;

    if (groupDetail.value.payAmount) {
        closeLoading();
        open();
        return;
    }

    if (isJoined && isVisitor.value) {
        if (joinOption.value === "NeedPermission") {

            await vistorQuit({
                groupId: groupId.value,
                userId: userData.id,
                silence:1,
            });
        } else {
            const result:any = await vistorToMember({
                groupId: groupId.value,
                userId: userData.id,
            });
            const { flag } = result;
            closeLoading();
            if (flag === 1) {
                uni.showToast({
                    icon: "none",
                    title: "已加入群",
                    duration: 1500,
                });

                setTimeout(() => {
                    uni.$emit("groupJoined");
                    goChat(true);
                }, 1000);
            } else {
                uni.showToast({
                    icon: "none",
                    title: "处理申请失败，请稍后再试",
                    duration: 2000,
                });
            }
            return;
        }
    }

    if (wording.value.trim()) {
        msg = wording.value;
    }
	
    //const checkAmount = await checkAndPayAmount()
	let params = {
		inviterId:inviterId.value,
		inviterName:inviterName.value,
		msg:msg
	}
	console.log(params)
    const result: any = await handleJoinGroup({
        groupID: groupId.value,
        msg:JSON.stringify(params)
    }).catch(() => {
        closeLoading();
    });

    if (isVisitor.value) {
        await vistorJoin({
            groupId: groupId.value,
            userId: userData.id,
            silence:1,
        });
    }

    const {
        data: { status },
    } = result;
    joinGroupLoading.value = false;

    console.log("status");
    console.log("status");
    console.log(status);

    closeLoading();
    if (status === "WaitAdminApproval") {
        uni.showToast({
            icon: "none",
            title: "已向群主发起申请，请耐心等待群主审核~",
            duration: 1500,
        });
        setTimeout(() => {
            goBack();
        }, 1500);
        return;
    }

    if (status === "JoinedSuccess") {
        uni.showToast({
            icon: "none",
            title: "已加入群",
            duration: 1500,
        });
        uni.$emit("groupJoined");
        goChat(true);
    }
};

const selectedPayType:any = ref({});

const selectPay = (item:any) => {
    selectedPayType.value = item;
};

let payLoading = false;

const checkAndPayAmount = async () => {
    const item = selectedPayType.value;

    if (!item.slimKey) {
        uni.showToast({
            icon: "none",
            title: "请选择支付方式",
            duration: 1500,
        });

        return;
    }

    if (!groupDetail.value.payAmount) {
        return true;
    }

    if(payLoading){
        return;
    }


    payLoading = true;

    uni.showLoading();

    const payParams = {
        slimType: 2,
        totalAmt: groupDetail.value.payAmount,
        productId: groupDetail.value.groupId,
        payType: Number(item.slimKey),
    };

    //let res = null;

    if (uni.platform === "ios") {
        res = await h5pay(payParams).catch(() => {
            uni.showToast({
                icon: "none",
                title: "支付失败",
                duration: 1500,
            });
            payLoading = false;
        });
    } else {
        res = await pay(payParams).catch(() => {
            // uni.showToast({
            //     icon: "none",
            //     title: "支付失败",
            //     duration: 1500,
            // });
            payLoading = false;
        });
    }
    checkStartTime = new Date().getTime();
    uni.$emit("groupJoined");
    if(!isChecking){
        checkJoinedAndGoGroup();
    }

};


let checkStartTime:any = null;
let isChecking = false;
let closeChecking = false;

const checkJoinedAndGoGroup = async () => {

    if(isChecking) {
        return;
    }

    if(closeChecking){
        return;
    }

    isChecking = true;

    if (checkStartTime) {
        let now = new Date().getTime();
        let timeDiff = now - checkStartTime;

        if (timeDiff > 300 * 1000) {
            isChecking = false;
            return;
        }
    }

    // const pages = getCurrentPages();
    // const page = pages[pages.length - 1];
    // const currentWebview = page.$getAppWebview();

    await GetGroupProfile();

    const isJoined: boolean = await isGroupJoined(
        userData.id,
        groupId.value
    ).catch(() => {}) as boolean;

    inGroup.value = isJoined;


    if (!isJoined) {
        setTimeout(() => {
            checkJoinedAndGoGroup();
        }, 1000);
        return;
    }

    if(isVisitor.value){
        setTimeout(() => {
            checkJoinedAndGoGroup();
        }, 1000);
        return;
    }

    closeLoading();
    uni.showToast({
        icon: "none",
        title: "已加入群",
        duration: 5000,
    });

    close();

    // setTimeout(()=>{
    //     uni.showToast({
    //             icon: "none",
    //             title: "webview close",
    //             duration: 5000,
    //         });
    //     currentWebview.close();
    // },500)

    goChat(true);



    //goChat(true);

    // /* #ifdef H5 */
    // uni.navigateTo({
    //     url: "/pages/quanzi/quanzi",
    // });
    // /*#endif*/

    // /*#ifdef APP-PLUS*/
    // uni.switchTab({
    //     url: "/pages/quanzi/quanzi",
    // });
    // /*#endif*/
};

const groupDetail:any = ref({});

const getDetail = async (groupId: string) => {
    console.log("getDetail");
    console.log(groupId);
    const res: any = await getCircleDetail({ groupId });
    const { flag, data } = res;
    if (flag !== 1) {
        uni.showToast({
            icon: "none",
            title: "获取群详情失败",
            duration: 3000,
        });

        return;
    }

    groupDetail.value = data;

    btnText.value = data.payAmount ? "支付并发送入群申请" : "发送入群申请";
};

const joinOption = ref("");
const GetGroupProfile = async () => {
    if (!uni.$chat_isSDKReady) {
        setTimeout(() => {
            return GetGroupProfile();
        }, 200);
        return;
    }
    const res:any = await getGroupProfile(groupId.value);

    joinOption.value = res.data.group.joinOption;
    let flag = false;

    const { memberCustomField } = res.data.group.selfInfo;
    if (memberCustomField.length) {
        memberCustomField.forEach((item:any) => {
            if (item.key === "role" && item.value === "Tourist") {
                flag = true;
            }
        });
    }
    isVisitor.value = flag;
};

const goChat = async (firstTimeInGroup: boolean) => {
    let hadChat = false;
    const pages = getCurrentPages();

    pages.forEach((page: any) => {
        if (page.route === "pages/TUIKit/TUIPages/TUIChat/index") {
            hadChat = true;
        }
    });

    if (hadChat) {
        uni.$emit("updateConversationGroupProfile");
        //closeWebview("pages/TUIKit/TUIPages/TUIChat/index");
        // 通知 TUIChat 关闭当前会话
        setTimeout(() => {
            handleJumpToChat(`GROUP${groupId.value}`, true, false);
        }, 1000);
    } else {
        handleJumpToChat(`GROUP${groupId.value}`, false, false);
    }
};

const goBack = () => {
    uni.navigateBack();
};

const needBack = ref(false);

const changeNeedBack = ()=>{
    needBack.value = true;
}


onShow(() => {
    payLoading = false;
    getDetail(groupId.value);
    GetGroupProfile();
    handleisGroupJoined();
    if(needBack.value){
        setTimeout(()=>{
            goBack();
        },500)
    }
});
const inviterId = ref("")
const inviterName = ref("")
onLoad((option: any) => {
    if (option.groupId) {
        groupId.value = option.groupId;
    }
	if (option.inviterId) {
	    inviterId.value = option.inviterId;
	}
	if (option.inviterName) {
	    inviterName.value = option.inviterName;
	}
    uni.$on('applyforgroupNeedBack',changeNeedBack);
});
onUnload(() => {
    closeChecking = true;
    uni.$off('applyforgroupNeedBack',changeNeedBack);
});
</script>
<style lang="scss" scoped>
.app {
    .header {
        position: fixed;
        width: 750rpx;
        z-index: 100;
        top: 0;
        left: 0;
        padding: 0 30rpx;
        display: flex;
        height: 100rpx;
        align-items: center;
        justify-content: space-between;
        height: 100rpx;
        // position: absolute;
        // top: 0;
        // left: 0;
        width: 750rpx;
        background-color: #ffffff;

        .right {
            width: 48rpx;
            height: 48rpx;
        }

        .firend {
            font-size: 34rpx;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 600;
            color: #000000;
        }
    }

    .bottom-popup {
        background: #ffffff;
        border-radius: 20rpx 20rpx 0rpx 0rpx;
        .popup-title {
            height: 100rpx;
            border-bottom: 1rpx solid #e4e4e4;
            .title-text {
                font-size: 32rpx;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #333333;
            }
            .title-icon {
                right: 30rpx;
                width: 36rpx;
                height: 36rpx;
            }
        }
        .popup-row {
            padding: 20rpx 30rpx 0 30rpx;
            .content-selected {
                position: relative;
                border: 2rpx solid rgba(29, 198, 145, 0.5);
            }
            .row-content {
                position: relative;
                padding: 30rpx 30rpx 30rpx 30rpx;
                box-shadow: 0rpx 2rpx 14rpx 0rpx rgba(0, 0, 0, 0.06);
                border-radius: 10rpx;
                overflow: hidden;
                border:2rpx solid transparent;
                &.selected {
                    border: 2rpx solid rgba(29, 198, 145, 0.5);
                }

                .selected-icon {
                    position: absolute;
                    top: -2px;
                    left: 0;
                    width: 40rpx;
                    height: 40rpx;
                }

                .content-img {
                    width: 100rpx;
                    height: 100rpx;
                }
                .content-type {
                    flex: 1;
                    padding-left: 20rpx;
                    .type-name {
                        height: 50rpx;
                        .name-text {
                            display: flex;
                            flex-direction: column;
                            align-items: flex-end;

                            font-size: 30rpx;
                            font-family: PingFangSC-Medium, PingFang SC;
                            font-weight: 500;
                            color: #333333;
                        }
                        .name-button {
                            margin-left: auto;
                            width: 80rpx;
                            height: 40rpx;
                            border-radius: 4rpx;
                            opacity: 0.99;
                            border: 1rpx solid #cccccc;

                            font-size: 24rpx;
                            font-family: PingFangSC-Regular, PingFang SC;
                            font-weight: 400;
                            color: #999999;
                        }
                    }
                    .type-describe {
                        padding-top: 12rpx;
                        height: 50rpx;
                        font-size: 24rpx;
                        font-family: PingFangSC-Regular, PingFang SC;
                        font-weight: 400;
                        color: #999999;
                        .describe-amount {
                            color: #1dc691;
                        }
                    }
                }
            }
        }
        .popup-button {
            margin-top:30rpx;
            .button-button {
                border-radius: 20rpx;
                left:25rpx;
            }
            .heightBox{
                width:750rpx;
                min-height:20rpx;
                height: constant(safe-area-inset-bottom);
                height: env(safe-area-inset-bottom);
            }
        }
    }

    .content {
        position: absolute;
        width: 750rpx;
        bottom: 0;
        left: 0;
        padding-bottom: calc(constant(safe-area-inset-bottom) + 20rpx);
        padding-bottom: calc(env(safe-area-inset-bottom) + 20rpx);
        .box {
            padding: 30rpx;
            background: #fff;
            .title {
                font-size: 30rpx;
                font-weight: 400;
                color: $slim-text3;
            }
            .amount {
                font-size: 30rpx;
                height: 100rpx;
                color: #333;
            }

            .warn {
                height: 100rpx;
                color: #eaa04f;
                font-size: 28rpx;
                gap: 10rpx;
                border-top: 1px solid #eee;
                .icon_warn {
                    width: 32rpx;
                    height: 32rpx;
                }
            }
        }

        .btn_main {
            position: fixed;
            bottom: calc(constant(safe-area-inset-bottom));
            bottom: calc(env(safe-area-inset-bottom));
            display: block;
            height: 80rpx;
            border-radius: 40rpx;
            line-height: 80rpx;
            z-index: 100;
            margin-top: 40rpx !important;
        }
    }
}
</style>    